package com.itbaima.csmall.order.webapi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.itbaima.csmall.commons.pojo.order.dto.OrderAddDTO;
import com.itbaima.csmall.commons.pojo.order.entity.Order;
import com.itbaima.csmall.commons.restful.JsonPage;
import com.itbaima.csmall.commons.restful.JsonResult;
import com.itbaima.csmall.commons.restful.ResponseCode;
import com.itbaima.csmall.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>订单控制器</p>
 *
 * @author Chen
 * @since 2023/2/20 13:23:23
 */
@RestController
@RequestMapping("/base/order")
@Api(tags = "订单模块")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @SentinelResource(value = "新增订单", blockHandler = "blockError", fallback = "fallbackError")
    @PostMapping("/add")
    @ApiOperation("新增订单的功能")
    public JsonResult<Void> orderAdd(OrderAddDTO orderAddDTO) {
        orderService.orderAdd(orderAddDTO);
        return JsonResult.ok("新增订单完成");
    }

    @GetMapping("/page")
    @ApiOperation("分页查询所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码", name = "page", example = "1"),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", example = "5")
    })
    public JsonResult<JsonPage<Order>> pageOrder(Integer page, Integer pageSize) {
        JsonPage<Order> ordersByPage = orderService.getAllOrdersByPage(page, pageSize);
        return JsonResult.ok("分页完成", ordersByPage);
    }

    public JsonResult<Void> blockError(OrderAddDTO orderAddDTO, BlockException blockException) {
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR, "服务器忙，请稍后再试！");
    }

    public JsonResult<Void> fallbackError(OrderAddDTO orderAddDTO, Throwable throwable) {
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR, "订单生成失败");
    }

}
